package com.briup.estore.web.filter;

import com.briup.estore.common.constant.ExceptionMsgEnum;
import com.briup.estore.common.exception.EstoreException;
import com.briup.estore.common.utils.JWTUtils;
import com.mysql.cj.util.LogUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author briup-adam
 * @Date 2023/8/2 下午2:23
 * @Description 请求过滤器 校验用户登录情况
 **/

@WebFilter(urlPatterns = "/*", filterName = "/EStoreFilter")
public class EStoreFilter implements Filter {
    private Logger log= Logger.getLogger(Log4JLogger.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        //输出拦截的请求
        String contextPath = request.getServletPath();
        String method = request.getMethod();
        log.info("登陆校验拦截器拦截到请求,请求方式为：" + method + "      请求路径为 :" + contextPath);

        switch (contextPath) {
//            登录注册请求直接放行
            case "/user/register":
            case "/user/login":

                break;
            default:
                String token = request.getHeader("token");
                //判断Token是否存在
                if (Objects.isNull(token) || token.equals("")) {
                    //没有Token
                    throw new EstoreException(ExceptionMsgEnum.USER_IS_NOT_LOGIN);
                }
                //token存在
                try {
                // 解析token
                    Claims jwt = JWTUtils.parseJWT(token);
                    String userId = jwt.getSubject();
                    request.setAttribute("userId", userId);
                } catch (ExpiredJwtException e) {
                    //用户登录过期
                    throw new EstoreException(ExceptionMsgEnum.USER_LOGIN_TIMEOUT);
                } catch (MalformedJwtException e) {
                    //登录令牌失效
                    throw new EstoreException(ExceptionMsgEnum.USER_TOKEN_IS_INVALID);
                } catch (Exception e) {
                    //服务器内部错误
                    throw new EstoreException(ExceptionMsgEnum.ERROR);
                }
                break;

        }
        log.info("请求放行");
        filterChain.doFilter(request, response);

    }


}
